import React, { Component } from 'react'
import axios from 'axios'
import PubSub from 'pubsub-js'
export default class Search extends Component {
  search = () => {
    // 1. 获取用户输入的关键词
    const {
      keyWordElement: { value: keyWord }
    } = this
    // 发送请求前通知 List 状态
    PubSub.publish('atguigu', {
      isFirst: false,
      isLoading: true,
      err: ''
    })
    // 2. 发送 ajax 请求
    axios
      .get(`https://api.github.com/search/users?q=${keyWord}`, {
        params: {
          q: keyWord
        }
      })
      .then(res => {
        console.log(res)
        // 请求成功后通知 List 状态
        PubSub.publish('atguigu', {
          isLoading: false,
          userList: res.data.items
        })
      })
      .catch(err => {
        // 请求失败后通知 List 状态
        PubSub.publish('atguigu', {
          isLoading: false,
          err: '请求失败'
        })
      })
  }

  render () {
    return (
      <section className='jumbotron'>
        <h3 className='jumbotron-heading'>搜索 Github 用户</h3>
        <div>
          <input
            ref={c => (this.keyWordElement = c)}
            type='text'
            placeholder='输入关键词点击搜索'
          />
          &nbsp;<button onClick={this.search}>搜索</button>
        </div>
      </section>
    )
  }
}
